package com.example.estest.controller;

import com.example.estest.entity.Order;
import lombok.AllArgsConstructor;
import org.apache.lucene.search.join.ScoreMode;
import org.elasticsearch.index.query.QueryBuilders;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.aggregation.AggregatedPage;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author whx
 * @date 2022/7/3
 */
@RestController
@RequestMapping("order")
@AllArgsConstructor
public class OrderController {

    private final ElasticsearchRestTemplate restTemplate;

    @GetMapping("listByProductName")
    public List<Order> listByProductName(int page, int size, String name){
        NativeSearchQueryBuilder queryBuilder = new NativeSearchQueryBuilder();
        queryBuilder.withQuery(QueryBuilders.nestedQuery("product",
                        QueryBuilders.termQuery("product.name",name), ScoreMode.Max))
                .withPageable(PageRequest.of(page, size));
        AggregatedPage<Order> orders = restTemplate.queryForPage(queryBuilder.build(), Order.class);
        return orders.getContent();
    }

}
